package com.example.baseutils.net;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;


import com.example.baseutils.NetUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Author by lp,on 2021/12/21/021,15:31.
 */
public class NetChangeReceiver extends BroadcastReceiver {
    private static final String TAG = "NetChangeReceiver";
    private List<NetListtenr> listtenrs = new CopyOnWriteArrayList<>();

    private boolean nowState = false;

    public boolean getNowState() {
        return NetUtil.isNetworkConnected();
    }

    public NetChangeReceiver(List<NetListtenr> listtenrs) {
        this.listtenrs = listtenrs;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connecttivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = null;
        if (connecttivityManager != null) {
            networkInfo = connecttivityManager.getActiveNetworkInfo();
        }
        if (networkInfo != null && networkInfo.isConnected()) {
            Log.e(TAG, "networks is isConnect");
            nowState = true;
        } else {
            Log.e(TAG, "networks is disConnect");
            nowState = false;
        }
        notifiy(nowState);
    }

    protected void notifiy(boolean state) {
        for (NetListtenr listtenr : listtenrs) {
            listtenr.netState(state);
        }
    }
}
